const fs = require('fs');
const path = require('path')

// 读取要检查的文件
const filePath = path.resolve(__dirname, './code.js');
const code = fs.readFileSync(filePath, 'utf8');

// 执行代码检查
const issues = checkCode(code);


// 输出检查结果
if (issues.length > 0) {
    issues.forEach((issue, index) => {
        console.log(`${index + 1}. 行 ${issue.lineNumber}: ${issue.message}`);
    });
} else {
   console.log('代码检查完毕，没有问题。');
}
 

/**
 * @param {String} code  code.js 文件内容
 * @return {Array} issues 存放问题的数组
 */
function checkCode(code) {
    // TODO：待补充代码
    const lines = code.split('\n');
    const issues = [];
    let variable = [];
    // 遍历每一行代码
    for (let i = 0; i < lines.length; i++) {
        const line = lines[i].trim(); // 每一行代码
        if (line == '') continue
        const regLog = /console.log/;
        const regLet = /^let /;
        const regConst = /^const /;
        const reg1 = /\[/;
        const regNum = /\d+/;
        const regVar = /var /;
        if (regLet.test(line) || regConst.test(line)) {
            const firstIndex = line.indexOf(' ');
            let rowline = firstIndex === -1 ? '' : line.substring(firstIndex + 1);
            rowline = rowline.replace(';','').replaceAll(' ','').split('=');
            rowline.forEach(item => {
                if (!reg1.test(item) && !regNum.test(item)) {
                    if (variable.indexOf(item) == -1) {
                        variable.push([item,0,null]);
                    }
                }
            });
        }
        if(regLog.test(line)) issues.push({lineNumber: i+1, message: '避免在生产代码中使用 console'});
        if(regVar.test(line))issues.push({lineNumber: i+1, message: '禁止使用 var 声明变量，推荐使用 let 或 const'});
    }
    lines.forEach((line,index) => {
        variable.forEach(item=> {
            if (line.includes(item[0]) || line.includes(item[0])) {
                item[1]++;
                item[2] = index + 1;
            }
          });
    });
    variable = variable.filter(item=>item[1] == 1);
    variable.forEach(item => {
        issues.push({lineNumber: item[2], message: `变量 ${item[0]} 定义未使用`});
    });
    issues.sort((a,b)=>a.lineNumber - b.lineNumber);
    return issues;
}

module.exports = checkCode;